<template>
  <div class="container" @click="resetSelection">
    <div id="map" class="map"></div>
    <div class="overlay">
      <div
        class="info-box"
        v-for="(info, index) in infos"
        :key="index"
        @click.stop="selectInfoBox(index)"
        :class="{ selected: selectedIndex === index }"
      >
        <div class="info-item bold" style="text-align: center;">运单号: {{ info.waybillNumber }}</div>
        <div class="info-item small-gray">
          <span>车牌号: {{ info.licensePlate }}</span>
          <span class="driver">司机: {{ info.driver }}</span>
        </div>
      </div>
    </div>
    <div v-if="selectedInfo" class="detail-overlay">
      <div class="detail-box">
        <div class="detail-item bold">运单号: {{ selectedInfo.waybillNumber }}</div>
        <div class="detail-item">车牌号: {{ selectedInfo.licensePlate }}</div>
        <div class="detail-item">司机: {{ selectedInfo.driver }}</div>
        <div class="detail-item">车辆位置: {{ selectedInfo.vehicleLocation }}</div>
        <div class="detail-item">发车时间: {{ selectedInfo.departureTime }}</div>
        <div class="detail-item">预计送达时间: {{ selectedInfo.estimatedDeliveryTime }}</div>
        <div class="detail-item">发货地: {{ selectedInfo.origin }}</div>
        <div class="detail-item">收货地: {{ selectedInfo.destination }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'BaiduMapComponent',
  data() {
    return {
      map: null,
      point: null,
      infos: [],
      selectedIndex: null, // 用于记录当前选中的 info-box 的索引
      driving: null, // 用于存储 DrivingRoute 实例
      lastClickTime: 0, // 用于记录上次点击的时间
      selectedInfo: null // 用于存储当前选中的详细信息
    };
  },
  mounted() {
    this.initMap();
    this.fetchInfos();
  },
  methods: {
    initMap() {
      // 创建地图实例
      this.map = new BMap.Map('map');

      // 添加比例尺控件
      this.map.addControl(new BMap.ScaleControl());

      // 创建点坐标
      this.point = new BMap.Point(116.404, 39.915);

      // 初始化地图，设置中心点坐标和地图级别
      this.map.centerAndZoom(this.point, 15);

      // 添加地图类型控件
      this.map.addControl(new BMap.MapTypeControl());

      // 设置地图显示的类型为普通道路图
      this.map.setMapType(BMAP_NORMAL_MAP);

      // 开启鼠标滚轮缩放
      this.map.enableScrollWheelZoom(true);



      // 创建标注
      // this.marker = new BMap.Marker(this.point);
      // this.map.addOverlay(this.marker);
    },
    fetchInfos() {
      axios.get('http://localhost:8901/trajectory/list')
        .then(response => {
          this.infos = response.data;
        })
        .catch(error => {
          console.error('获取数据失败:', error);
        });
    },
    selectInfoBox(index) {
      const now = Date.now();
      if (now - this.lastClickTime < 1000) {
        return; // 如果距离上次点击时间不足1秒，忽略这次点击
      }
      this.lastClickTime = now; // 更新上次点击时间

      this.selectedIndex = index; // 更新选中的 info-box 索引
      this.drawRoute(index);
    },
    async drawRoute(index) {
      // 清除之前的路径
      if (this.driving) {
        this.driving.clearResults();
      }

      const info = this.infos[index];
      const origin = info.origin;
      const vehicleLocation = info.vehicleLocation;
      const destination = info.destination;

      const geocoder = new BMap.Geocoder();

      try {
        const startPoint = await this.geocodeAddress(geocoder, origin);
        const viaPoint = await this.geocodeAddress(geocoder, vehicleLocation);
        const endPoint = await this.geocodeAddress(geocoder, destination);

        this.driving = new BMap.DrivingRoute(this.map, {
          renderOptions: { map: this.map, autoViewport: true }
        });

        this.driving.search(startPoint, endPoint, { waypoints: [viaPoint] });

        // 为经过点添加点击事件监听器
        this.driving.setMarkersSetCallback(markers => {
          console.log('Markers:', markers); // 添加日志输出
          markers.forEach(marker => {
            if (marker instanceof BMap.Marker) {
              marker.addEventListener('click', () => {
                this.selectedInfo = info;
              });
            } else {
              console.warn('Invalid marker:', marker); // 添加日志输出
            }
          });
        });

        // 确保路径绘制完成后再更新选中的详细信息
        this.selectedInfo = info;
      } catch (error) {
        console.error('地址解析失败:', error);
      }
    },
    geocodeAddress(geocoder, address) {
      return new Promise((resolve, reject) => {
        geocoder.getPoint(address, point => {
          if (point) {
            console.log(`地址解析成功: ${address}`, point); // 添加日志输出
            resolve(point);
          } else {
            console.error(`无法解析地址: ${address}`); // 添加日志输出
            reject(new Error(`无法解析地址: ${address}`));
          }
        }, '全国');
      });
    },
    resetSelection() {
      this.selectedIndex = null;
      this.selectedInfo = null;
    }
  }
}
</script>

<style scoped>
.container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  padding: 30px; /* 可选：添加一些内边距 */
}

.map {
  width: 1000px; /* 固定宽度 */
  height: 800px;
}

.overlay {
  position: absolute;
  top: 90px;
  left: 180px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 5px;
  z-index: 1000; /* 确保浮动层在地图之上 */
  display: flex;
  flex-direction: column;
  gap: 10px; /* 小盒子之间的间距 */
}

.info-box {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 280px; /* 设置宽度 */
  height: 100px; /* 设置高度 */
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  cursor: pointer; /* 鼠标悬停时显示指针 */
}

.info-item {
  margin-bottom: 5px;
  display: flex;
  align-items: center; /* 垂直居中 */
}

.bold {
  font-weight: bold;
}

.small-gray {
  font-size: 12px; /* 字体缩小 */
  color: gray; /* 颜色为灰色 */
}

.driver {
  margin-left: 10px; /* 车牌号和司机之间的间距 */
}

/* 选中状态的样式 */
.selected {
  border: 2px solid blue;
  background-color: #e6f1ff;
  color: #006eff;
}

.detail-overlay {
  position: absolute;
  top: 540px;
  right: 1%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 1001; /* 确保浮动层在地图之上 */
  width: 300px;
}

.detail-box {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-item {
  font-size: 14px;
  color: #333;
}
</style>
